package com.doctor.controller.admin;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.doctor.common.JsonResult;
import com.doctor.controller.BaseController;
import com.doctor.entity.Department;
import com.doctor.entity.Doctor;
import com.doctor.lucene.SearcherKit;
import com.doctor.service.DeparmentService;
import com.doctor.service.DoctorService;

@Controller
@RequestMapping("/admin/doctor")
public class DoctorController extends BaseController {

    @Resource
    private DoctorService doctorService;
    @Resource
	private DeparmentService deparmentService;
    @Resource
	private SearcherKit searcherKit;

    @GetMapping("/index")
    public String index() {
        return "admin/doctor/index";
    }
    
    @GetMapping("/view")
    public String view(ModelMap map) {
        List<Doctor> list = doctorService.findAllMan();
        map.put("list", list);
        return "admin/doctor/view";
    }

    @PostMapping("/list")
    @ResponseBody
    public Page<Doctor> list() {
        PageRequest pageRequest = getPageRequest();
        Page<Doctor> page = doctorService.findAll(pageRequest);
        return page;
    }

    @GetMapping("/form")
    public String form(@RequestParam(required = false) Long id, ModelMap map) {
    	List<Department> list = deparmentService.findAll();
		map.put("list", list);
		
        if (id != null) {
            Doctor Doctor = doctorService.findById(id);
            map.put("doctor", Doctor);
        }
        return "admin/doctor/form";
    }

    @PostMapping("/save")
    @ResponseBody
    public JsonResult save(Doctor Doctor) {
        try {
            if (Doctor != null) {
                doctorService.saveOrUpdate(Doctor);
    			//添加或修改博客后重新生成索引
    			searcherKit.reloadIndex(doctorService.findAllMan());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.fail(e.getMessage());
        }
        return JsonResult.ok();
    }

    @PostMapping("/{id}/del")
    @ResponseBody
    public JsonResult delete(@PathVariable Long id) {
        try {
            doctorService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.fail(e.getMessage());
        }
        return JsonResult.ok();
    }

}
